﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using XuanFe.Database.Common;
using XuanFe.Database.DAL;
using XuanFe.Database.Model;

namespace XuanFe.Database.BLL
{
    public class StaffBLL : AbstractBase
    {
        private static StaffBLL instance = new StaffBLL();
        /// <summary>
        /// 初始化实例
        /// </summary>
        /// <returns></returns>
        public static StaffBLL Instance
        {
            get
            {
                return instance;
            }
        }
        public StaffBLL() : base() { }
        /// <summary>
        /// 员工登录。0：成功；1：失败；2：账号不存在；3：密码不正确；4：账号未生效；5：已离职；6：角色不存在。
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="password"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Login(LoginModel login, out StaffLogonModel model)
        {
            model = null;
            DateTime now = GlobalParamDAL.Instance.GetSystemTime();
            StaffModel staff = StaffDAL.Instance.Get(login.StaffId);
            if (staff == null)
            {
                // 账号不存在
                return 2;
            }
            if (!string.Equals(staff.Password, login.Password, StringComparison.OrdinalIgnoreCase))
            {
                // 密码不正确
                return 3;
            }
            if (staff.JoinDate.Date > now.Date)
            {
                // 账号未生效
                return 4;
            }
            if (staff.Dimission)
            {
                // 已离职
                return 5;
            }
            RoleModel role = RoleDAL.Instance.Get(staff.RoleId);
            if (role == null)
            {
                // 角色不存在
                return 6;
            }

            string sessionId = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
            StaffActiveModel active = new StaffActiveModel() { StaffId = login.StaffId, LoginTime = now, ComputerName = login.ComputerName, IPAddress = login.IPAddress, MACAddress = login.MACAddress, SessionId = sessionId };

            using (DbConnection db = MySQLHelper.Instance.CreateConnection())
            {
                try
                {
                    db.Open();

                    using (DbTransaction tran = db.BeginTransaction())
                    {
                        try
                        {
                            StaffActiveDAL.Instance.SetLastLogoutTime(tran, login.StaffId, login.ComputerName, now);
                            StaffLoginStateDAL.Instance.Delete(tran, login.StaffId, login.ComputerName);
                            StaffActiveDAL.Instance.Insert(tran, active);
                            StaffLoginStateDAL.Instance.Insert(tran, new StaffLoginStateModel() { StaffId = login.StaffId, LoginTime = now, ComputerName = login.ComputerName, IPAddress = login.IPAddress, MACAddress = login.MACAddress, SessionId = sessionId });

                            List<ModuleModel> modules = ModuleDAL.Instance.GetFromRole(staff.RoleId);
                            List<FunctionModel> functions = FunctionDAL.Instance.GetFromRole(staff.RoleId);
                            model = new StaffLogonModel(sessionId, login, staff, role, modules, functions);

                            tran.Commit();

                            return 0;
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            if (this.Logger.IsErrorEnabled)
                            {
                                this.Logger.Error("登录系统发生异常", ex);
                            }
                            return 1;
                        }
                    }
                }
                finally
                {
                    db.Close();
                }
            }
        }
        public int Logout(LoginModel login)
        {
            DateTime now = GlobalParamDAL.Instance.GetSystemTime();

            using (DbConnection db = MySQLHelper.Instance.CreateConnection())
            {
                try
                {
                    db.Open();

                    using (DbTransaction tran = db.BeginTransaction())
                    {
                        try
                        {
                            StaffActiveDAL.Instance.SetLastLogoutTime(tran, login.StaffId, login.ComputerName, now);
                            StaffLoginStateDAL.Instance.Delete(tran, login.StaffId, login.ComputerName);

                            tran.Commit();

                            return 0;
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            if (this.Logger.IsErrorEnabled)
                            {
                                this.Logger.Error("退出系统发生异常", ex);
                            }
                            return 1;
                        }
                    }
                }
                finally
                {
                    db.Close();
                }
            }
        }
        public int UpdatePassword(StaffModel model)
        {
            using (DbConnection db = MySQLHelper.Instance.CreateConnection())
            {
                try
                {
                    db.Open();

                    using (DbTransaction tran = db.BeginTransaction())
                    {
                        try
                        {
                            StaffDAL.Instance.UpdatePassword(tran, model);

                            tran.Commit();

                            return 0;
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            if (this.Logger.IsErrorEnabled)
                            {
                                this.Logger.Error("修改密码发生异常", ex);
                            }
                            return 1;
                        }
                    }
                }
                finally
                {
                    db.Close();
                }
            }
        }
    }
}
